from PIL import Image, ImageDraw, ImageFont

# 设置文件路径
txt_file_path = "../story/story_20250321_1.txt"  # 你的txt文件路径
output_image_prefix = "story_part"  # 输出图片的前缀

# 使用Mac自带的苹方字体
font_path = "/System/Library/AssetsV2/com_apple_MobileAsset_Font7/b86e58f38fd21e9782e70a104676f1655e72ebab.asset/AssetData/Yuanti.ttc"

# 图片尺寸（小红书常用尺寸）
image_width = 1000
image_height = 1420

# 字体大小
font_size = 45

# 边距
margin = 50

# 每页最大行数
max_lines_per_page = 20

# 读取txt文件内容
with open(txt_file_path, "r", encoding="utf-8") as file:
    story = file.read()

# 自动换行函数
def wrap_text(text, font, max_width, draw):
    lines = []
    paragraphs = text.split('\n')  # 按段落分割
    for paragraph in paragraphs:
        if paragraph.strip() == "":  # 如果是空行，直接添加到 lines
            lines.append("")
            continue
        current_line = ""
        for word in paragraph.split():
            # 检查当前行加上新单词是否会超出最大宽度
            test_line = current_line + word + " "
            test_width = draw.textlength(test_line, font=font)
            if test_width <= max_width:
                current_line = test_line
            else:
                # 如果当前行不为空，先保存当前行
                if current_line:
                    lines.append(current_line.strip())
                # 如果单词本身超出最大宽度，强制换行
                if draw.textlength(word, font=font) > max_width:
                    # 将长单词拆分成多个部分
                    for i in range(0, len(word), max_width // font_size):
                        lines.append(word[i:i + max_width // font_size])
                else:
                    current_line = word + " "
        # 保存最后一行
        if current_line:
            lines.append(current_line.strip())
    return lines

# 按行数分页
def split_into_pages(lines, max_lines_per_page):
    pages = []
    current_page = []
    for line in lines:
        current_page.append(line)
        if len(current_page) >= max_lines_per_page:
            pages.append(current_page)
            current_page = []
    # 添加最后一页（如果有剩余行）
    if current_page:
        pages.append(current_page)
    return pages

# 生成图片
def generate_image(page_lines, page_number):
    # 创建一张空白图片
    image = Image.new('RGB', (image_width, image_height), color=(255, 255, 255))
    draw = ImageDraw.Draw(image)

    # 加载字体
    font = ImageFont.truetype(font_path, font_size)

    # 计算文本位置
    x = margin
    y = margin

    # 逐行绘制文本
    for line in page_lines:
        if line == "":  # 如果是空行，增加行间距
            y += font_size + 10
        else:
            draw.text((x, y), line, font=font, fill=(0, 0, 0))
            y += font_size + 10  # 行间距

    # 保存图片
    image.save(f'story_3/{output_image_prefix}_{page_number + 1}.png')

# 创建临时图片和 draw 对象用于计算文本宽度
temp_image = Image.new('RGB', (image_width, image_height), color=(255, 255, 255))
temp_draw = ImageDraw.Draw(temp_image)
temp_font = ImageFont.truetype(font_path, font_size)

# 自动换行并分页
lines = wrap_text(story, font=temp_font, max_width=image_width - 2 * margin, draw=temp_draw)  # 先调用 wrap_text 生成所有行
pages = split_into_pages(lines, max_lines_per_page)  # 按行数分页

# 生成每页图片
for i, page in enumerate(pages):
    generate_image(page, i)

print(f"图片生成完成！共生成 {len(pages)} 张图片。")